package com.qdlc.p2p.biz.processor.task;

import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.qdlc.p2p.biz.executer.impl.RechargeSuccessExecuter;
import com.qdlc.p2p.biz.processor.event.QuickPayValueEvent;
import com.qdlc.p2p.biz.service.AccountRechargeService;
import com.qdlc.p2p.common.constant.RechargeStatus;
import com.qdlc.p2p.common.core.queue.TaskProcessorException;
import com.qdlc.p2p.common.core.queue.ValueEvent;
import com.qdlc.p2p.common.core.queue.annotation.ScheduledProcessor;
import com.qdlc.p2p.common.util.LogFactory;
import com.qdlc.p2p.dal.dao.AccountRechargeDao;
import com.qdlc.p2p.dal.dto.AccountRecharge;
import com.qdlc.p2p.dal.dto.User;
import com.qdlc.p2p.dal.model.AccountRechargeModel;

/**
 * 快捷支付任务处理(新浪)
 * @author linya 2016-01-04
 */
@Service
@ScheduledProcessor(delay=10)
public class QuickPayTaskProcessor extends AbstractTaskProcessor {
	
	private static final Logger logger = LogFactory.QUICK_PAY_LOGGER;
	
	@Resource
	AccountRechargeService accountRechargeService;
	
	@Resource
	private AccountRechargeDao accountRechargeDao;
	
	@Override
	public boolean supports(ValueEvent event) {
		return event instanceof QuickPayValueEvent;
	}
	
	@Override
	public boolean hasTransaction() {
		return true;
	}

	@Override
	protected void process0(ValueEvent event) throws TaskProcessorException {
		QuickPayValueEvent payEvent = (QuickPayValueEvent)event;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		System.out.println("++++ QuickPay, Time:" + sdf.format(new Date()));
		String orderId = payEvent.getOrderId();
		User user = payEvent.getUser();
		double money = payEvent.getMoney();
		RechargeStatus status = payEvent.getStatus();
		AccountRecharge recharge = payEvent.getAccountRecharge();
		logger.info(MessageFormat.format("++++用户{0}充值{1}成功，订单号{2}", user.getUserName(), money, orderId));
		
		//处理充值业务
		if(RechargeStatus.SUCCESS == status){
			recharge.setStatus(AccountRechargeModel.RECHARGE_SUCCESS);
			//添加资金记录
			RechargeSuccessExecuter rechargeSuccessExecuter = new RechargeSuccessExecuter();
			rechargeSuccessExecuter.setMoney(money);
			rechargeSuccessExecuter.setRecharge(recharge);
			rechargeSuccessExecuter.execute(user);
			accountRechargeDao.update(recharge);
		}else if(RechargeStatus.FAILED == status){
			recharge.setStatus(AccountRechargeModel.RECHARGE_FAIL);
			recharge.setReturnMsg(payEvent.getErrorMessage());
			accountRechargeDao.update(recharge);
		}
		
	}

}
